package jude.java.money.service;

import java.util.List;

import jude.java.money.beans.ScanFtp;
import jude.java.money.beans.Site;
import jude.java.money.beans.Site2;
import jude.java.money.beans.WeakPassword;
import jude.java.money.beans.WebUrl;

public class ScanService extends BaseService {
	
	public boolean save(Site site) {
		Site s = get(Site.class, "host", site.getHost());
		if (s != null)
			return false;
		insert(site);
		return true;
	}
	
	public boolean save(WebUrl url) {
		WebUrl s = get(WebUrl.class, "url", url.getUrl());
		if (s != null)
			return false;
		insert(url);
		return true;
	}
	
	public boolean save(ScanFtp ftp) {
//		System.out.println("\t\t" + ftp.getHost());
		ScanFtp s = get(ScanFtp.class, "host", ftp.getHost());
		if (s != null)
			return false;
		insert(ftp);
//		try {
//			insert(ftp);
//		} catch (Throwable e) {
//			return false;
//		}
		return true;
	}
	
	public synchronized List<WebUrl> listUnScannedUrls() {
		List<WebUrl> urls = null;
		synchronized (this) {
			urls = query(WebUrl.class, "o.status=?", 3, 0, WebUrl.STATE_NEW);
			for (WebUrl url : urls) {
				url.setStatus(WebUrl.STATE_SCANNING);
				update(url);
			}
		}
		return urls;
	}
	
	
	public List<Site> listSites(int pageSize, int pageIndex){
		return query(Site.class, null, pageSize, pageIndex, null, null);
	}
	
	public List<Site> listScanFtpPortSites(int pageSize, int pageIndex){
		return query(Site.class, "o.status=?", pageSize, pageIndex, Site.STATUS_NEW);
	}
	
	public List<Site2> listScanFtpPortSites2(int pageSize, int pageIndex){
		return query(Site2.class, "o.status=?", pageSize, pageIndex, Site.STATUS_NEW);
	}
	
	public int countNewScanFtpSites() {
		return count(ScanFtp.class, "o.state=?", ScanFtp.STATE_NEW);
	}
	
	public List<ScanFtp> listScanFtpPassportSites(int pageSize, int pageIndex) {
		return query(ScanFtp.class, "o.state!=? and o.state!=?", pageSize, pageIndex, new Object[] {ScanFtp.STATE_FTP, ScanFtp.STATE_IGNORE}, null);
//		return query(ScanFtp.class, "o.state=?", pageSize, pageIndex, ScanFtp.STATE_NEW);
//		String limit = pageSize * pageIndex + "," + pageSize;
//		return dao.queryBySql("select {o.*} from tb_scanftp2 o, tb_ftp_site b where o.host = b.host and o.state!=0 and o.state!=1 and b.logined=0 " + limit, ScanFtp.class);
	}
	
	public int countSites(int status) {
		return count(Site.class, "o.status=?", status);
	}
	
	public List<WeakPassword> listWeakPasswords(int pageSize, int pageIndex, int[] levels) {
		if (levels == null || levels.length == 0)
			return query(WeakPassword.class, null, pageSize, pageIndex, null);
		Object[] ls = new Object[levels.length];
		for (int i = 0; i < ls.length; i++) {
			ls[i] = levels[i];
		}
		return dao.queryWithArray(WeakPassword.class, pageSize, pageIndex, "level in (:array)", ls);
	}
}
